#include <stdio.h>
 #include <unistd.h>  

#include "socket_handler.h" 
#include "epoll_handler.h"

int main()
{
	SocketHandler socketHandler("10.1.1.131", 6666);
	if(!socketHandler.SocketBind()) {
		return -1;
	}
	if(!socketHandler.SocketListen()) {
		return -1;
	}

	int listenFd = socketHandler.GetListenFd();

	EpollHandler epollHandler;
	epollHandler.EpollInit();
	epollHandler.AddEvent(listenFd, EPOLLIN);
	printf("listenFd:%d\n", listenFd);
	for(;;){
		int num = epollHandler.WaitEpoll();
		for(int i = 0; i < num; i ++) {
			int fd = epollHandler.CheckInEvent(i);
			if(fd >= 0 && fd == listenFd) {
				int chilFd = socketHandler.HandlerAccept();
				if(chilFd > 0) {
					printf("===========Get accept from client!!!=========\n");
					epollHandler.AddEvent(chilFd, EPOLLIN);
				}
			} else if (fd >= 0){
				string str = socketHandler.DoRead(fd);
				printf("get str:%s\n", str.c_str());
				if(str.size()) {
					epollHandler.ModifyEvent(fd, EPOLLOUT);
				} else {
					epollHandler.DeleteEvent(fd, EPOLLIN);
				}
			}

			fd = epollHandler.CheckOutEvent(i);
			if(fd > 0) {
				bool ret = socketHandler.DoWrite(fd, "Bak!!!\n");
				if(ret) {
					epollHandler.ModifyEvent(fd, EPOLLIN);
				} else {
					 epollHandler.DeleteEvent(fd, EPOLLOUT);
				}
			}
		}
	}

	epollHandler.EpollUinit();
	socketHandler.SocketUinit();

	return 0;
}
